import React from 'react';
import styles from './index.module.scss';
import { update } from '@/utils/immutableUtil';
import _ from 'lodash';
import { X } from 'lucide-react';
import { withConsumer } from '../../../context';

@withConsumer
class Comp extends React.Component {
  state = {
    files:[]
  };
  componentDidMount = () => {
    const {
      value: { setController },
    } = this.props;
    setController('UploadFiles', this);
  };
  render() {
    const { files } = this.state
    console.log(files)
    return (
      <div>
        {files.length > 0 && (
          <div className={styles.container}>
            {files.map((file, i) => {
              return (
                <div className={styles.item} key={file.name}>
                  <span
                    onClick={() => {
                      var newFiles = [...files];
                      var key = newFiles[i].name
                      newFiles.splice(i, 1);
                      this.setState({files:newFiles})
                    }}
                    className={
                      styles.close +
                      ' absolute top-[-8] right-[-8] bg-muted rounded-full p-1'
                    }
                  >
                    <X className="h-3 w-3 cursor-pointer" />
                  </span>
                  <img
                    src={URL.createObjectURL(file)}
                    alt={file.name}
                    className="rounded-xl w-10 h-10 object-cover"
                  />
                </div>
              );
            })}
          </div>
        )}


          <input
            type="file"
            id="multimodal"
            name="multimodal"
            accept="image/*"
            multiple={true}
            className="hidden"
            onChange={(e)=>{
              var attr = [...e.target.files]
              var files = [...this.state.files]
              files.push(...attr)
              var multimodal = document.getElementById('multimodal');
              if(multimodal){
                  multimodal.value = ''
              }

              this.setState({files:files},()=>{
               
                var This = this
                files.forEach((file,i)=>{
                  // 创建 FileReader 实例
                  const reader = new FileReader();
                  
                  // 当文件读取完成时触发此事件
                  reader.onload = function(e2) {
                    // e.target.result 就是 Base64 格式的字符串
                    const base64String = e2.target.result;
                    // 显示 Base64 字符串（实际项目中可能需要限制显示长度）
                    This.state.files[i].baseUrl = base64String
                    console.log(This.state.files)
                  };
  
                  reader.readAsDataURL(file);
                })  

              })

              

            }}
          />

      </div>
    );
  }
}

export default Comp;
